// pages/confirmOrder/confirmOrder.js
const app = getApp()
let request = require('../../utils/request.js')
let addFlag = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    agreementShow: false,
    carNumList: [],
    checkCarIndex: 0,
    inputLen: 8,
    activeIptIndex: -1,
    carNo: '',
    addCarDialog: false,
    couponDialog: false,
    couponList: [],
    couponIndex: -1,
    checkedCouopn: {},
    totalPrices: 0,
    subtract: 0,
    btnLoading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let data = JSON.parse(options.payData)
    console.log('会员卡信息：', data)
    this.setData({
      orderData: data
    })
    if (data.type == 'MONTH') {
      this.getCarNumList()
    } else if (data.type == 'DURATION') {

    } else if (data.type == 'CUSTOMIZE') {
      this.getCarNumList()
    } else if (data.type == 'skype') {
      this.setData({
        'orderData.type': 'RECHARGE'
      })
    }
    this.getCoupon()
  },
  /**
   * 查询优惠券
   */
  getCoupon() {
    let that = this
    let url = '/customer/ticket/getNotExpiredValidTicket'
    let type = this.data.orderData.type
    let parmas = {
      cardType: type == 'RECHARGE' ? 4 : type == 'MONTH' ? 3 : 1,
      amount: this.data.orderData.paidAmount
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let coupon = data.data
          for (var i = 0; i < coupon.length; i++) {
            coupon[i].checked = false
          }
          that.setData({
            couponList: coupon
          })
        }
      })
  },
  /**
   * 选择优惠券
   * @param {*} e 
   */
  getDiscount(e) {
    let index = e.currentTarget.dataset.index
    let couponIndex = this.data.couponIndex
    let coupon = this.data.couponList
    if (index == couponIndex) {
      coupon[index].checked = false
      this.setData({
        checkedCouopn: {},
        couponIndex: -1,
        subtract: 0
      })
    } else {
      for (var i = 0; i < coupon.length; i++) {
        if (index == i) {
          coupon[i].checked = true
        } else {
          coupon[i].checked = false
        }
      }
      this.setData({
        checkedCouopn: coupon[index],
        couponIndex: index
      })
    }
    this.setData({
      couponList: coupon
    })
    if (this.data.checkedCouopn.ticketId) {
      this.countCoupon()
    }
    this.hideCouponDialog()
  },
  /**
   * 计算优惠价格
   */
  countCoupon() {
    let that = this
    let url = '/customer/ticket/getDiscountAmontWithTicket'
    let parmas = {
      paidAmount: this.data.orderData.paidAmount,
      receivableAmount: this.data.orderData.paidAmount,
      ticketId: this.data.checkedCouopn.ticketId,
      custTicketId: this.data.checkedCouopn.id,
      rentType: this.data.orderData.type == 'MONTH' ? 0 : this.data.orderData.type == 'RECHARGE' ? 4 : 2,
      customerId: wx.getStorageSync('lmtc_customerId')
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            totalPrices: data.data.paidAmount,
            subtract: data.data.discountAmount
          })
        }
      })
  },
  /**
   * 显示优惠券弹窗
   */
  showCouponDialog() {
    if (this.data.couponList.length <= 0) {
      wx.showToast({
        title: '暂无优惠券可用',
        icon: 'none'
      })
      return
    }
    this.setData({
      couponDialog: true
    })
  },
  /**
   * 隐藏优惠券弹窗
   */
  hideCouponDialog() {
    this.setData({
      couponDialog: false
    })
  },
  /**
 * 查询车牌列表
 */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i].select = true
              } else {
                list[i].select = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },
  /**
   * 选择车辆
   */
  checkCar(e) {
    let index = e.currentTarget.dataset.index
    let carNumList = this.data.carNumList
    for (var i = 0; i < carNumList.length; i++) {
      carNumList[i].select = false
      if (index == i) {
        carNumList[i].select = true
      }
    }
    this.setData({
      checkCarIndex: index,
      carNumList: carNumList
    })
  },
  // 显示添加车牌号弹窗
  showAddCarDialog() {
    this.setData({
      addCarDialog: true
    })
  },
  /**
   * 隐藏添加车牌号弹窗
   */
  diddenAddCarDialog() {
    this.setData({
      addCarDialog: false
    })
  },
  /**
  * 输入车牌号
  */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: that.data.carNo.length
    });
  },
  /**
   * 键盘输入操作
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘隐藏事件
   */
  handleHiddenCarPlate() {
    this.setData({
      showPlateInput: false,
      activeIptIndex: -1
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
  * 判断车牌号
  * @param {String} value 车牌号
  */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加车牌号
   */
  addCarNumber() {
    if (addFlag) {
      return
    }
    let that = this;
    let carNo = that.data.carNo;
    if (!that.isCarPlate(that.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return;
    }
    addFlag = true
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        let data = res.data
        if (data.code == 200) {
          console.log(data);
          wx.showToast({ title: '添加成功' })
          that.setData({ carNo: '' })
          that.getCarNumList();
          that.handleHiddenCarPlate()
          that.diddenAddCarDialog()
        } else {
          // wx.showToast({ title: '添加失败，请稍后重试！', icon: 'none' })
        }
        addFlag = false
      }).catch((errMsg) => {
        addFlag = false
      });
  },
  /**
   * 支付
   */
  payment() {
    this.setData({ btnLoading: true })
    let that = this
    let _this = this
    let orderData = this.data.orderData
    let carNumList = this.data.carNumList
    let checkCarIndex = this.data.checkCarIndex
    let url = ''
    let params = {}
    //  充值余额
    if (orderData.type == 'RECHARGE') {
      url = '/customer/card/recharge'
      let payMoney = that.data.subtract ? that.data.totalPrices : orderData.paidAmount
      console.log(orderData.paidAmount)
      console.log(payMoney)
      params = {
        receivableAmount: orderData.paidAmount,
        paidAmount: payMoney <= 0 ? 0.01 : payMoney,
        custTicketId: that.data.checkedCouopn.id ? that.data.checkedCouopn.id : ''
      }
      request.http(url, 'POST', params, 0)
        .then(res => {
          if (res.data.code == 200) {
            let orderCode = res.data.data.orderCode
            //支付
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
              nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
              package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
              signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
              paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
              success: function (res) { // 成功后的回调函数
                wx.showToast({ title: '充值成功' })
                _this.setData({ btnLoading: false })
                wx.redirectTo({ url: '/pages/chargeRecord/chargeRecord' })
              },
              fail(res) {
                console.log(res)
                _this.setData({ btnLoading: false })
               }
            })
          } else {
            _this.setData({ btnLoading: false })
          }
        })
      return
    }
    //  月租卡
    if (orderData.type == 'MONTH') {
      url = '/customer/card/buyMonthCard'
      if (carNumList.length <= 0) {
        wx.showToast({ title: '请您先绑定车牌，在进行购买', icon: 'none' })
        return
      }
      params = {
        carId: carNumList[checkCarIndex].id,
        monthRentType: orderData.monthRentType,
        monthRuleId: orderData.monthRuleId,
        uniformRentType: orderData.uniformRentType,
        paidAmount: orderData.paidAmount <= 0 ? 0.01 : orderData.paidAmount,
        parkId: orderData.parkList.id
      }
    //  时长卡
    } else if (orderData.type == 'DURATION') {
      url = '/customer/card/buyDurationCard'
      params = {
        durationRuleFeeScaleId: orderData.durationRuleFeeScaleId,
        durationRuleId: orderData.durationRuleId,
        paidAmount: orderData.paidAmount <= 0 ? 0.01 : orderData.paidAmount
      }
    //  订单月租卡
    } else if (orderData.type == 'CUSTOMIZE') {
      let parkIds = []
      for (let i = 0; i < orderData.parkList.length; i++) {
        parkIds.push(orderData.parkList[i].id);
      }
      url = '/customer/card/buyCustomizeCard'
      params = {
        carId: carNumList[checkCarIndex].id,
        parkIdList: parkIds,
        paidAmount: orderData.paidAmount <= 0 ? 0.01 : orderData.paidAmount,
        monthRentType: orderData.monthRentType,
      }
    }
    if (this.data.subtract) {
      params.paidAmount = this.data.totalPrices <= 0 ? 0.01 : this.data.totalPrices
      params['ticketId'] = this.data.checkedCouopn.ticketId
      params['custTicketId'] = this.data.checkedCouopn.id
    }
    request.http(url, 'POST', params)
      .then(res => {
        if (res.data.code == 200) {
          // if (that.data.subtract && that.data.totalPrices == 0) {
          //   wx.showToast({
          //     title: '开通成功，下次停车即可享用服务',
          //   })
          //   wx.redirectTo({
          //     url: '../grade/grade'
          //   })
          // } else {
          let orderCode = res.data.data.orderCode
          //支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
            paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) { // 成功后的回调函数
              _this.setData({ btnLoading: false })
              that.getPayState(orderData.type, orderCode)
            },
            fail(res) {
              console.log(res)
              _this.setData({ btnLoading: false })
             }
          })
        } else {
          console.log(res)
          _this.setData({ btnLoading: false })
        }
        // }
      })
  },
  /**
   * 查询支付状态
   */
  getPayState(cardType, orderCode) {
    let url = '/customer/card/validatePayState'
    let parmas = {
      cardType: cardType,
      orderCode: orderCode
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        if (res.data.code) {
          wx.showToast({ title: '开通成功，下次停车即可享用服务' })
          wx.redirectTo({ url: '../grade/grade' })
        } else {
          wx.showToast({ title: '开通失败，请联系平台客服', icon: 'none' })
        }
      })
  },
  /**
   * 用户协议弹窗
   */
  showAgreement() {
    this.setData({
      agreementShow: true
    })
  },
  /**
   * 关闭用户协议弹窗
   */
  showAgreementClose() {
    this.setData({
      agreementShow: false
    })
  }
})